var qoola = (function($, _) {	
	$.template = {
			// tweet : _.template($('#tweetTemplate').text()),
			//ustadz : _.template($('#ustadzTemplate').html()),
			mediaLink : _.template($('#mediaLinkTemplate').html()),
			urlEntity : _.template($('#urlEntityTemplate').html()),
			urlLink : _.template($('#urlLinkTemplate').html()),
			imgLink : _.template($('#imgLinkTemplate').html()),
			urlLinkWithTitle : _.template($('#urlLinkWithTitleTemplate').html()),
			hashTagLink : _.template($('#hashTagLinkTemplate').html()),
			shortConversation : _.template($('#tweetShortConversationTemplate').html()),
			tweetPopular : _.template($('#tweetPopularTemplate').html()),
			conversation : _.template($('#convTemplate').html())//,
			// noConversation : _.template($('#noConvTemplate').text())
	};
	var _topTweepsUrl = "getTopRank.php";
	var _topTweetsUrl = "getPopularTweets.php";
	var _tweetsSelector = "#top-tweets";
	var _tweepsSelector = "#top-tweeps";
	var _withMasonry = true;
	var _withInfiniteScroll = true;
	var _tweetsMasonryOptions = { itemSelector : '.tweet', //columnWidth: 196
			columnWidth: function(containerWidth){
				return (containerWidth / $.constant.masonryColumns);
			}
	,  isResizable: true
	};
	var _tweetsInfiniteScrollOptions = {
			//debug: true,
			dataType: 'json',
			// path: $.fullPath(_topTweetsUrl) + "?page=",
			navSelector  : '#twitter-page-nav',    // selector for the paged navigation 
			nextSelector : '#twitter-page-nav a',  // selector for the NEXT link (to page 2)
			itemSelector : '.tweet',     // selector for all items you'll retrieve
			loading: {
				finishedMsg: 'Semua posting telah ditampilkan.',
				selector : "#loading-container",
				img: $.fullPath("/ico/loading.gif"),
				msgText: "<em>Tampilkan kumpulan tweet berikutnya...</em>"
			},
			animate : true,
			localMode    : true, 
            appendCallback : false,
			template: function(data) {
				var msg = "";
				if(data != null)
					for(var i=0;i<data.length;i++)
						msg +=renderTopTweetItem(data[i]);				
				return msg;
			}
	};
	var bindEvents = function() {
		$.subscribe("topTweets/dataRetrieved", renderTopTweets);
		$.subscribe("tweet/action/showConversation", showTweetConversation);
		$.subscribe("tweet/action/reply", replyTweet);
		$.subscribe("tweet/action/retweet", reTweet);
		var $tweetSelector = $(_tweetsSelector);		
		$tweetSelector.on("click", function(e){
			var $target = $(e.target).closest(".tweet_action", $tweetSelector);
			if($target.length) {
				e.preventDefault();
				var targetId = $target.attr("id"); // only check for those with id.
				if(targetId != undefined || targetId != null) {
					if(_.str.startsWith(targetId,"conversation_")){
						e.stopPropagation();
						$.publish("tweet/action/showConversation", targetId);
					} else if(_.str.startsWith(targetId,"reply_")){
						e.stopPropagation();
						$.publish("tweet/action/reply", targetId);
					} else if(_.str.startsWith(targetId,"retweet_")){
						e.stopPropagation();
						$.publish("tweet/action/retweet", targetId);
					} 
				}
				return false;
			}
		});

	};
	var replyTweet = function(e, idSelector) {
		//window.console && console.log ("TODO: replyTweet "+ idSelector);
		var statusid = idSelector.split("_")[1];
		if(statusid != undefined || statusid != null) {
			var windowWidth = 550;
			var windowHeight = 350;
			var centerWidth = (window.screen.width - windowWidth) / 2;
			var centerHeight = (window.screen.height - windowHeight) / 2;
			var url = "https://twitter.com/intent/tweet?in_reply_to="+statusid+"&via=qultweet.com";
			replyWindow = window.open(url,"twitter_web_intent",'resizable=1,width=' + windowWidth + 
					',height=' + windowHeight + 
					',left=' + centerWidth + 
					',top=' + centerHeight);

		}
	};
	var reTweet = function(e, idSelector) {
		//window.console && console.log ("TODO: reTweet "+ idSelector);
		var statusid = idSelector.split("_")[1];
		if(statusid != undefined || statusid != null) {
			var windowWidth = 550;
			var windowHeight = 350;
			var centerWidth = (window.screen.width - windowWidth) / 2;
			var centerHeight = (window.screen.height - windowHeight) / 2;
			var url = "https://twitter.com/intent/retweet?tweet_id="+statusid+"&via=qultweet.com";
			replyWindow = window.open(url,"twitter_web_intent",'resizable=1,width=' + windowWidth + 
					',height=' + windowHeight + 
					',left=' + centerWidth + 
					',top=' + centerHeight);
		}
	};
	var showUstadzProfile = function(){
		
		
	};
	var showTweetConversation = function(e, idSelector) {
		window.console && console.log ("TODO: showTweetConversation "+ idSelector);
		var theConvId = idSelector.split("_")[1];
			var $confDialog = $('#conv_dialog');
			var $loader = $('#conv-loading-container');
			$confDialog.empty();

			$loader.show();
		$.get($.fullPath("getConversations.php")+ "?convid="+theConvId,	function( data) {
			
			var markupconv = '<div class="simplemodal-close" style="position:absolute;right:5px;"><a style="color:white;margin-bottom:5px" href=""><img style="width:17px;vertical-align:top;"src="ico/Close.ico"> Tutup</a></div><br/>';
			var position = $('#'+idSelector).position();
			/*var el_height = $convIdDiv.parent().parent().height();*/
			for ( var i = 0; i < data.length; i++) {
				//conversion entities
				//include all the links of the entities into the text
				var txt = data[i].text;
				if(data[i].media_url != null && data[i].media_url.length > 0 ){
					for(var k = 0 ; k < data[i].media_url.length; k++){
						var medurl = '<a href="'+data[i].media_expanded_url[k]+'" target="_blank">'+ data[i].media_expanded_url[k] +'</a>';
						txt = txt.replace(data[i].text.substr(data[i].media_index_start[k],
								response[i].media_index_end[k]-response[i].media_index_start[k]),medurl);
					}
				}
				if(data[i].url_entity != null && data[i].url_entity.length > 0){
					for(var k = 0 ; k < data[i].url_entity.length; k++){
						var enturl = '<a href="'+data[i].url_entity[k]+'" target="_blank">' 
						+ data[i].url_entity[k] +'</a>';
						//txt = txt.replace(response[i].text.substr(response[i].url_index_start[k],response[i].url_index_end[k] - response[i].url_index_start[k]),enturl);				
						txt = txt.replace(data[i].url_entity[k],enturl);
					}
				}
				if(data[i].hashtag_text != null && data[i].hashtag_text.length > 0){
					for(var k = 0 ; k < data[i].hashtag_text.length; k++){
						if(data[i] == null || data[i].hashtag_text == null || data[i].hashtag_text[k] == null){
							continue;
						}
						var enturl = '<a href="http://twitter.com/#!/search/%23'+data[i].hashtag_text[k]+'" target="_blank">'
						+ '#'+data[i].hashtag_text +'</a>';
						//txt = txt.replace(response[i].text.substr(response[i].hash_start[k],response[i].hash_end[k]-response[i].hash_start[k]),enturl);
						if(txt != null && txt.length > 0){
							txt = txt.replace('#'+data[i].hashtag_text[k],enturl);
						}
					}
				}
				if(data[i].mentioned_screen_name != null){
					for(var k = 0 ; k < data[i].mentioned_screen_name.length ; k++){
						//var mentioned = '<a href="http://twitter.com/\#!/'+data[i].mentioned_screen_name[k]+'" target="_blank">'+ '@'+data[i].mentioned_screen_name[k] +'</a>';
						var mentioned = '@'+data[i].mentioned_screen_name[k];
						//txt = txt.replace(response[i].text.substr(response[i].mention_start[k],response[i].mention_end[k]-response[i].mention_start[k]),mentioned);
						if(txt != null && txt.length > 0){
							txt = txt.replace('@'+data[i].mentioned_screen_name[k],mentioned);
						}					
						
					}
				}
				//------------------------------------
				//Include all the entities into the tweet
				var entities = [];
				if(data[i].url_entity != null && data[i].url_entity.length > 0){
					for(var k = 0 ; k < data[i].url_entity.length; k++){
						entities.push(data[i].expanded_url[k] != null ? data[i].expanded_url[k] : data[i].url_entity[k]);
					}
				} 
				var medias = [];
				if(data[i].media_url != null && data[i].media_url.length > 0){
					for(var k = 0 ; k < data[i].media_url.length; k++){
						medias.push({url : data[i].media_url[k], width : data[i].size_small_w[k], height : data[i].size_small_h[k]});	
					}
				}
				//-----------------------------------------
				markupconv += $.template.conversation({ isTop : (i == 0), is_ustadz : data[i].is_ustadz
					,topPosition : 0
					, text : txt, profile_img_url : data[i].profile_img_url, 
					name : (data[i].name != undefined && data[i].name != null) ? data[i].name : data[i].display_name, screen_name: data[i].screen_name,
							medias : medias, entities : entities, created_at : data[i].created_at, status_id :data[i].statusid
				});
			}
			//markupconv += '<div class="tweet_conv"><div class="triangle-border right"><div id="conv_comment_box"></div><div style="clear: both;"></div></div>';

			//markupconv += '</div>';
			if(data.length == 0){
				markupconv = $.template.noConversation({topPosition : (position.top-(el_height*0.8))});
			}
			//$('#conv_dialog' ).dialog( "destroy" );
			$confDialog.empty(); // why? how about the html that has been appended above?
			
			//$('#content').fadeTo('slow',0.4);
		
			$confDialog.html(markupconv);			
			if($confDialog.is(":hidden")) $confDialog.show();
			
			//$('#conv_dialog').css('background-color','black');
			$confDialog.modal({
				modal: true,
				resizable: true,
				minHeight : 500,
				maxHeight : 500,
				maxWidth : 652,
				minWidth : 652,
				opacity : 40,
				overlayCss: {backgroundColor:"#000"},
				overlayClose:true,
				position: ['25%','25%'],
				autoPosition: true,
				autoResize: true,
				close : true,
				zIndex :12000,
				onShow : function(dialog) {
					//$("#opaque").show();
					$loader.hide();
					dialog.overlay.fadeIn('fast', function () {
						dialog.data.hide();
						dialog.container.fadeIn('fast', function () {
							dialog.data.slideDown('fast');
							$("body").css("overflow", "hidden");
							twttr.anywhere(function (T) {
					    	   T.hovercards({ expanded: true});
					    	});
							$('#conv_dialog').jScrollPane(
									{
										showArrows: true,
										autoReinitialise: true,
										horizontalGutter: 10,
								
									}
								);
						});
					});
				   
				},
				onClose : function(dialog) {
					//$("#opaque").hide();
					//$('#conv_dialog').modal({opacity: 1});
					
					// dialog.data.fadeOut('fast', function () {
						// dialog.container.slideUp('fast', function () {
							// dialog.overlay.fadeOut('fast', function () {
								// $.modal.close(); // must call this!
								// $("body").css("overflow", "auto");
							// });
						// });
					// });

					dialog.data.fadeOut('fast', function () {
						dialog.container.hide('fast', function () {
							dialog.overlay.slideUp('fast', function () {
								$.modal.close(); // must call this!
								$('#conv_dialog').unbind().empty().hide();
								$("body").css("overflow", "auto");
							});
						});
					});
					//$.modal.close();
					//$('#content').css('opacity',1);
				}
				

			});
			
	}, "json");	
};
var loadTopTweets = function(offset, firstTime) {
	window.console && console.log ("loadTopTweets... firstTime " + firstTime + ", offset " + offset);
	if(firstTime == undefined) firstTime = false;
	$.getJSON($.fullPath(_topTweetsUrl) + "?page=OFFSET".replace(/OFFSET/, offset), function(data) {
		$.publish("topTweets/dataRetrieved", [data, firstTime]);
	});
};
var loadPopularTweeps = function() {
	window.console && console.log ("loadPopularTweeps");
	$.getJSON($.fullPath(_topTweepsUrl), function(data) {
		$.publish("topTweeps/dataRetrieved", data.top_ustadz);
	});
};
var renderTopTweeps = function(e, topTweeps) {
	// $(_tweepsSelector).populateWithTemplateItem(topTweeps, $.template.ustadz);
	// $.publish("topTweeps/dataRendered", topTweeps);
}
var renderTopTweetItem = function(item) {
	var txt = item.text;
	if(txt == null) {
		window.console && console.log("text is null");
		return null;
	}	
	if(item.media_url != null){						
		for(var k = 0 ; k < item.media_url.length; k++){
			var medurl = $.template.mediaLink({url: item.media_expanded_url[k]}); 
			txt = txt.replace(item.text.substr(item.media_index_start[k],item.media_index_end[k]-item.media_index_start[k]),medurl);
		}
	}
	if(item.url_entity != null){
		for(var k = 0 ; k < item.url_entity.length; k++){
			if(item.url_entity[k] == null) {
				window.console && console.log("item.url_entity[k] is null");
				continue;
			}
			var enturl = $.template.urlLink({url: item.url_entity[k]});
			txt = txt.replace(item.url_entity[k],enturl);
		}
	}
	if(item.hashtag_text != undefined && item.hashtag_text != null){
		for(var k = 0 ; k < item.hashtag_text.length; k++){
			if(item.hashtag_text[k] == null) {
				window.console && console.log("item.hashtag_text[k] is null");
				continue;
			}
			var enturl = $.template.hashTagLink({url: item.hashtag_text[k]});
			txt = txt.replace('#'+item.hashtag_text[k],enturl);
		}
	}
	if(item.mentioned_screen_name != null){		
		for(var k = 0 ; k < item.mentioned_screen_name.length ; k++){
			var mentioned = '@'+item.mentioned_screen_name[k];
			txt = txt.replace('@'+item.mentioned_screen_name[k],mentioned);								
		}
	}
	//------------------------------------
	//Include all the entities into the tweet
	var entities = [];
	if(item.url_entity != null && item.url_entity.length > 0){
		for(var k = 0 ; k < item.url_entity.length; k++){
			entities.push({url_entity: item.url_entity[k], page_title : item.page_title[k],
				noembed_title: item.noembed_title[k], fb_thumbnail_url : item.fb_thumbnail_url[k],
				noembed_thumbnail_url : item.noembed_thumbnail_url[k], page_image : item.page_image[k],
				fb_page_desc : item.fb_page_desc[k],page_image : item.page_image[k],
				page_desc : item.page_desc[k], expanded_url : item.expanded_url[k]
			});
		}
	} 

	var medias = [];
	if(item.media_url != null && item.media_url.length > 0){
		for(var k = 0 ; k < item.media_url.length; k++){
			medias.push({url : item.media_url[k], width : item.size_small_w[k], 
				height : item.size_small_h[k]});

		}
	}

	var conversations = [];
	if(item.conv_statusid != null && item.conv_statusid.length > 0){
		for(var k = 0 ; k < item.conv_statusid.length;k++){
			conversations.push({status_id: item.conv_statusid[k], screen_name: item.conv_screen_name[k]
			,text: item.conv_text[k], name: ((item.conv_name[k]!=undefined)?item.conv_name[k] : item.conv_screen_name[k]) 
			,conv_profile_img_url: item.conv_profile_img_url[k],created_at: item.conv_created_at[k]
			});
		}
	}
	//-----------------------------------------

	return $.template.tweetPopular({ text : txt, 
		profile_img_url : item.profile_img_url, name : item.name, display_name : item.display_name, screen_name : item.screen_name,
		medias : medias, entities : entities, created_at : item.created_at,
		convid : item.convid, convid_count: item.convid_count, status_id : item.statusid, conversations : conversations
	});
}

var _addMasonryItem = function(items, callback) {
	var $cntr = $(_tweetsSelector);
	if(items.length == 0) {
		if(callback != undefined) callback();
		if($cntr.data('infinitescroll') != undefined)$cntr.data('infinitescroll').showEffectOnFinishedLoad();
		window.console && console.log("resume infinite scroll");
		return;
	}
	// window.console && console.log ("add masonry item. left : " + items.length);
	var $item = $("#"+items.shift());
	$item.imagesLoaded(function(){
		$item.css({ opacity: 1 });
		$cntr.masonry( 'appended', $item);
		_addMasonryItem(items, callback);
	});
}
var renderTopTweets = function(e, response, firstTime) {
	var rLength = response.length;
	window.console && console.log ("renderTopTweets... count : "+ rLength + ", firstTime" + firstTime);
	var markup = "";	
	var items = new Array();	
	if(firstTime) {
		$(document).ready(function(){

			if(_withMasonry) {	
				window.console && console.log ("setup masonry .");
				$(_tweetsSelector).masonry(_tweetsMasonryOptions);
				var $container = $(_tweetsSelector); 	
				for ( var i = 0; i < rLength; i++) {				
					// markup += renderTopTweetItem(response[i]);
					var text = renderTopTweetItem(response[i]);
					var item = $(text);
					item.css({ opacity: 0 });
					$container.append(item);
					items.push(item.attr('id'));
				}
				_addMasonryItem(items, function() {

					if(firstTime) {       		
						if(_withInfiniteScroll) {
							var $theCntr = $(_tweetsSelector); 
							window.console && console.log ("setup infinite scroll." + $theCntr.attr("id"));
							$theCntr.infinitescroll(_tweetsInfiniteScrollOptions,
									// trigger Masonry as a callback
									function( newElements ) {
								// hide new items while they are loading
									if(newElements.length == 0) {
										$theCntr.data('infinitescroll').done();
										return;
									}
									var $newElems = $( newElements ).css({ opacity: 0 });
									var newItems = new Array();
									$newElems.each(function(){
										var item = $(this);
										item.css({ opacity: 0 });
										$theCntr.append(item);
										newItems.push(item.attr('id'));
									});
									_addMasonryItem(newItems);
									twttr.anywhere(function (T) {
										T.hovercards({ expanded: true});
									});
								
							}
							);
							window.console && console.log ("finish setup infinite scroll." + $theCntr.attr("id"));
						}
					}
				});
			}
		});
	}	

	//$.publish("topTweeps/dataRendered", topTweeps);

}

return {
	replyTweet : replyTweet,
	reTweet : reTweet,
	showUstadzProfile : showUstadzProfile,
	showTweetConversation: showTweetConversation,
	renderTopTweeps : renderTopTweeps,
	renderTopTweets : renderTopTweets,
	loadTopTweets : loadTopTweets,
	bindEvents : bindEvents,
	getTweetsSelector : function() {return this._tweetsSelector; },
	setTweetsSelector : function(val) {this._tweetsSelector = val; },
	getTweepsSelector : function() {return this._tweepsSelector; },
	setTweepsSelector : function(val) {this._tweepsSelector = val; },
	useMasonry : function(val) {this._withMasonry = val;},
	useInfiniteScroll: function(val) {this._withInfiniteScroll = val;},
	init : function() {			
		this.bindEvents();
		this.loadTopTweets(1, true); // page #1 .. first time.
	}
}
})(jQuery, _);

window.app = window.app || {};
window.app.qoola = qoola;
